package com.siecom.client;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.snackbar.Snackbar;
import com.siecom.client.adapter.DeviceItemAdapter;
import com.siecomzg.constconfig.ConstDefine;
import com.siecomzg.tool.LogUtil;
import com.siecomzg.transport.usb.USBClient;
import com.siecomzg.transport.usb.receiver.OpenDevicesReceiver;
import com.siecomzg.transport.usb.receiver.UsbDetachedReceiver;
import com.siecom.zhq.client.R;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

//import ccb.ygqd.inspur.common.CommonHF;
//import ccb.ygqd.inspur.common.ConstHF;
public class BtDeviceActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener,
        UsbDetachedReceiver.UsbDetachedListener, OpenDevicesReceiver.OpenDevicesListener , View.OnClickListener {
    private static final String TAG = BtDeviceActivity.class.getSimpleName();

    public RecyclerView mRecyclerView;
    public LinearLayoutManager mLayoutManager;

    public List<BluetoothDevice> dataset;
    public DeviceItemAdapter mAdapter;
    public SwipeRefreshLayout mSwipeRefreshWidget;
    private BluetoothReciever _bluetoothReceive = null;

    private TextView mUSbNameTV;
    private Button mBtnConnectUsb,mBtnSend;
    private LinearLayout mLLUsbConn;

    private BluetoothAdapter localBluetoothAdapter;
    private final String STATE_CHANGED = "android.bluetooth.adapter.action.STATE_CHANGED";

    private Switch mSwitch;
    private UsbDevice mUsbDevice;
    public UsbDetachedReceiver mUsbDetachedReceiver;
    public OpenDevicesReceiver mOpenDevicesReceiver;
    private static final String USB_ACTION = "com.siecom.zhq.client";
    public UsbManager mUsbManager ;
    public USBClient mUSBClient ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        LogUtil.setLogEnabled(false);  //日志输出开关
        mUSBClient = USBClient.getInstance(getApplicationContext());

        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        mSwitch = (Switch) toolbar.findViewById(R.id.switch_usb_bt);
        mSwitch.setOnCheckedChangeListener(mSwithChangeListener);

        setSupportActionBar(toolbar);
        findView();

        if (getSupportActionBar() != null){
            getSupportActionBar().setTitle(getResources().getString(R.string.bt_scan));
        }
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);

        mRecyclerView = (RecyclerView) findViewById(R.id.device_item_list);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);

        mSwipeRefreshWidget = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_widget);
        mSwipeRefreshWidget.setOnRefreshListener(this);

        localBluetoothAdapter = BluetoothAdapter
                .getDefaultAdapter();
        if (!(localBluetoothAdapter.isEnabled()))
            startActivity(new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE"));

        initBt();
        checkPermission();
        InitializeBluetoothAdapter();
//        CrashHandler.getInstance().init(this);
//        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
//        mUsbDetachedReceiver = new UsbDetachedReceiver(this);
//        IntentFilter intentFilter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED);
//        intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
//        intentFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
//        intentFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
//        registerReceiver(mUsbDetachedReceiver, intentFilter);
//
//        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(USB_ACTION), 0);
//        IntentFilter intentFilter1 = new IntentFilter(USB_ACTION);
//        mOpenDevicesReceiver = new OpenDevicesReceiver(this);
//        registerReceiver(mOpenDevicesReceiver, intentFilter1);

        mSwitch.setChecked(false);
//        final Common common = new Common(BtDeviceActivity.this);
//        common.setCommuMethod(ConstHF.CONN_TYPE_BLUE);
//        startFindBt();
    }
    public void findView(){
//        Toast.makeText(this,"启动成功",Toast.LENGTH_SHORT).show();
        mBtnConnectUsb = (Button) findViewById(R.id.btn_connect_accessory);
        mBtnSend = (Button) findViewById(R.id.btn_usb_send_msg);
        mUSbNameTV = (TextView) findViewById(R.id.tv_usb_accessory_name);
        mBtnSend.setOnClickListener(this);
        mBtnConnectUsb.setOnClickListener(this);
        mLLUsbConn = (LinearLayout) findViewById(R.id.ll_usb_connect);
    }

    private void startFindBt() {
        if (localBluetoothAdapter != null && !localBluetoothAdapter.isDiscovering()) {
            LogUtil.e("start", "find");
            localBluetoothAdapter.startDiscovery();
        }
    }

    public void initBt() {
        if (dataset == null)
            dataset = new ArrayList<>();

        bluetoothAdapterMgr();
        if (mAdapter == null) {
            mAdapter = new DeviceItemAdapter(this, dataset);
            mRecyclerView.setAdapter(mAdapter);
        }
        mAdapter.notifyDataSetChanged();
        this._bluetoothReceive = new BluetoothReciever();


    }

    @Override
    public void onRefresh() {
        Snackbar.make(mSwipeRefreshWidget, getResources().getString(R.string.btScan), Snackbar.LENGTH_LONG).setAction("Action", null).show();
        startFindBt();
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_connect_accessory:
                Intent intent = new Intent();
                intent.setClass(BtDeviceActivity.this,DeviceActivity.class);
                intent.putExtra("Device", mUsbDevice);
                intent.putExtra("type","2"); // 1 是蓝牙设备   2 为 USB设备



//                ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(activity,
//                        Pair.create(itemView.findViewById(R.id.device_icon), "device_icon"),
//                        Pair.create(itemView.findViewById(R.id.device_name), "device_name"));

                startActivity(intent);
                break;
            case R.id.btn_usb_send_msg:
                LogUtil.e(TAG,"onclick send" );
               int i= mUSBClient.sendTest();
                if(i > 0){
                    Toast.makeText(this,"发送成功" ,Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(this,"发送失败" ,Toast.LENGTH_SHORT).show();
                }
                break;

                default:
                    break;
        }
    }


    // 用广播接收器来更新蓝牙扫描的状态
    private class BluetoothReciever extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            String name = "" ;
            if (device != null)
                name = device.getName() == null ? "" : device.getName();
            LogUtil.e(TAG,"接收到广播消息：" + action + "-----" + name);

            switch (action) {
                case BluetoothDevice.ACTION_FOUND:
                    boolean isPresence = false;
                    try {
                        for (int i = 0; i < dataset.size(); i++) {
                            if (dataset.get(i).getAddress().equals(device.getAddress())) {
                                isPresence = true;
                                break;
                            } else {
                                isPresence = false;
                            }
                        }
                        if (!isPresence) {
                            if(device.getName() != null){
                                dataset.add(device);
                                mAdapter.notifyDataSetChanged();
                            }
                        }
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                    break;

                case BluetoothDevice.ACTION_BOND_STATE_CHANGED:

                    LogUtil.e("bt", "ACTION_BOND_STATE_CHANGED");
                    if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                        Snackbar.make(mSwipeRefreshWidget, device.getName() + getResources().getString(R.string.btBond) + getResources().getString(R.string.please_click), Snackbar.LENGTH_LONG).setAction("Action", null).show();

                    }
                    break;
                case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                    LogUtil.e("bt", "ACTION_DISCOVERY_FINISHED");
                    mSwipeRefreshWidget.setRefreshing(false);

                    break;
                case STATE_CHANGED:

                    initBt();

                    break;

                case BluetoothDevice.ACTION_ACL_CONNECTED:
                    LogUtil.e(TAG,"ACTION_ACL_CONNECTED---- ");
                    break;

                case BluetoothDevice.ACTION_ACL_DISCONNECTED:
                    LogUtil.e(TAG,"ACTION_ACL_DISCONNECTED---- ");
                    break;

            }

        }
    }

    private void InitializeBluetoothAdapter() {

        IntentFilter localIntentFilter = new IntentFilter();
        localIntentFilter.addAction("android.bluetooth.device.action.FOUND");
        localIntentFilter
                .addAction("android.bluetooth.device.action.BOND_STATE_CHANGED");
        localIntentFilter
                .addAction("android.bluetooth.adapter.action.SCAN_MODE_CHANGED");
        localIntentFilter
                .addAction("android.bluetooth.adapter.action.STATE_CHANGED");
        localIntentFilter
                .addAction("android.bluetooth.device.action.PAIRING_REQUEST");
        localIntentFilter
                .addAction("android.bluetooth.adapter.action.DISCOVERY_STARTED");
        localIntentFilter
                .addAction("android.bluetooth.adapter.action.DISCOVERY_FINISHED");
        localIntentFilter.addAction("android.hardware.usb.action.USB_DEVICE_ATTACHED");
        localIntentFilter.addAction("android.hardware.usb.action.USB_DEVICE_DETACHED");
        localIntentFilter.addAction("android.hardware.usb.action.USB_STATE");
        localIntentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        localIntentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        if (!_bluetoothReceive.isOrderedBroadcast())
            this.registerReceiver(this._bluetoothReceive, localIntentFilter);


    }

    @Override
    protected void onPause() {
        super.onPause();

        try{
            this.unregisterReceiver(this._bluetoothReceive);
        } catch (Exception e){
            // already unregistered
        }

    }

    private void bluetoothAdapterMgr() {

        if (localBluetoothAdapter != null) {
            Set<?> localSet = localBluetoothAdapter.getBondedDevices();
            dataset.clear();
            if (localSet.size() > 0) {
                int i = 0;
                Iterator<?> localIterator = localSet.iterator();
                while (true) {
                    if (!(localIterator.hasNext()))
                        return;
                    BluetoothDevice localBluetoothDevice = (BluetoothDevice) localIterator
                            .next();
                    LogUtil.i("BLEDevice", "Paired devices [" + i + "]: name->"
                            + localBluetoothDevice.getName() + ", address->"
                            + localBluetoothDevice.getAddress());
                    if(localBluetoothDevice.getName().startsWith(ConstDefine.DEVICE_PREX) ||
                            localBluetoothDevice.getName().startsWith(ConstDefine.DEVICE_PREX1) ||
                            localBluetoothDevice.getName().startsWith(ConstDefine.DEVICE_PREX2)
                    ){  //过滤设备
                        dataset.add(localBluetoothDevice);
                    }
                }
            }

        }
    }

    private CompoundButton.OnCheckedChangeListener mSwithChangeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if(b){ // true 选中为红色状态  USB连接
                //恒丰测试需要
//                final CommonHF common = new CommonHF(BtDeviceActivity.this);
//                common.setCommuMethod(ConstHF.CONN_TYPE_USB);
                LogUtil.e(TAG,"切换状态为：" + b + "USB连接");
                mSwitch.setText("已切换为USB连接模式");
                mRecyclerView.setVisibility(View.GONE);
                mLLUsbConn.setVisibility(View.VISIBLE);

//                 new Common(BtDeviceActivity.this).setCommuMethod(ConstHF.CONN_TYPE_USB);
//                int ret = mUSBClient.openDevices();
//                if (ret == 0){
//                    ConstDefine.CONNECT_TYPE = ConstDefine.CONNECT_TYPE_USB; //USB连接
//                }
//                openDevices();

            }else { //false 默认 灰色状态  蓝牙连接状态
                //恒丰测试需要
//                final CommonHF common = new CommonHF(BtDeviceActivity.this);
//                common.setCommuMethod(ConstHF.CONN_TYPE_BLUE);

                LogUtil.e(TAG,"切换状态为：" + b + "蓝牙连接");
                mSwitch.setText("已切换为蓝牙连接模式");
                mRecyclerView.setVisibility(View.VISIBLE);
                mLLUsbConn.setVisibility(View.GONE);
//                new Common(BtDeviceActivity.this).setCommuMethod(ConstHF.CONN_TYPE_BLUE);
                ConstDefine.CONNECT_TYPE = ConstDefine.CONNECT_TYPE_BLUE; //蓝牙连接
            }
        }
    };
    //检测到USB拔出
    @Override
    public void usbDetached() {
        LogUtil.e(TAG,"usbDetached 检测到被拔出");
        Toast.makeText(this,"usbDetached" ,Toast.LENGTH_SHORT).show();
        mUSBClient.disConnect();
    }
    public void usbAttached(){
        LogUtil.e(TAG,"usbAttached 检测到usb 插入.....");
        mUSBClient.openDevices();
    }
    //打开USB AccessoryModel
    @Override
    public void openAccessoryModel(UsbDevice usbDevice) {
        mUsbDevice = usbDevice;
        LogUtil.e(TAG,"openAccessoryModel----------------" + mUsbDevice.getProductId());
//        Toast.makeText(this,"openAccessoryModel" ,Toast.LENGTH_SHORT).show();

        mUSBClient.initAccessory(usbDevice);
        mUSbNameTV.setText("A108Plus");
    }

    // 打开错误
    @Override
    public void openDevicesError() {
        LogUtil.e(TAG,"openDevicesError");
        Toast.makeText(this,"openDevicesError" ,Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        try{
            this.unregisterReceiver(this._bluetoothReceive);
        } catch (Exception e){
            // already unregistered
            LogUtil.e(TAG,"unregisterReceiver error==" + e.getMessage());
        }
        try{
            this.unregisterReceiver(mOpenDevicesReceiver);
        } catch (Exception e){
            // already unregistered
            LogUtil.e(TAG,"unregisterReceiver error==" + e.getMessage());
        }
        try{
            this.unregisterReceiver(mUsbDetachedReceiver);
        } catch (Exception e){
            // already unregistered
            LogUtil.e(TAG,"unregisterReceiver error==" + e.getMessage());
        }
        mUSBClient.disConnect();


    }

    /**
     * android API23以上需要检查权限
     */
    private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
    public void checkPermission() {
        Log.e("click", "checkPermission");
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.ACCESS_COARSE_LOCATION,
                            Manifest.permission.ACCESS_FINE_LOCATION
                    },
                    1);
        } else {
            initBt();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                Toast.makeText(this, "Permission ok", Toast.LENGTH_SHORT).show();
                initBt();

            } else {

                // Permission Denied
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
            return;
        } else {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                Toast.makeText(this, "Permission ok", Toast.LENGTH_SHORT).show();

//                updateBin();

            } else {

                // Permission Denied
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }

        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

}
